package com.itcast.stargraph.config;

import com.itcast.stargraph.api.ComfyuiApi;
import com.itcast.stargraph.handler.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * Comfyui配置类
 *
 * @Author katana
 * @Date 2025/6/8 15:26
 */
@Configuration
public class ComfyuiConfig {
    
    @Value("${comfyuiHost}")
    private String comfyuiHost;
    
    @Bean
    public ComfyuiApi getComfyuiApi(){
        
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();
        
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://" + comfyuiHost)
                .client(client)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(ComfyuiApi.class);
    }
    
    
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler) {
        WebSocketClient webSocketClient = new StandardWebSocketClient();
        String url = "ws://"+comfyuiHost+"/ws?clientId=star-graph";
        WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(webSocketClient,comfyuiMessageHandler,url);
        webSocketConnectionManager.start();
        return webSocketConnectionManager;
    }
}
